import { create } from 'zustand';
import { authApi } from '../services/cloud/api/authApi';
import { message } from 'antd';
import { persist } from 'zustand/middleware';
import type { Tenant, TenantUser, TenantLoginRequest, TenantContext } from '../types/tenant';

interface TenantState extends TenantContext {
  // 当前用户信息（多租户版本）
  currentUser: TenantUser | null;
  
  // 认证token
  token: string | null;
  
  // 租户相关操作
  setCurrentTenant: (tenant: Tenant) => void;
  setAccessibleTenants: (tenants: Tenant[]) => void;
  setCurrentUser: (user: TenantUser) => void;
  setToken: (token: string) => void;
  
  // 租户登录和认证
  tenantLogin: (loginData: TenantLoginRequest) => Promise<void>;
  logout: () => void;
  
  // 权限检查方法
  hasPermission: (permission: string, resourceContext?: any) => boolean;
  hasRole: (role: string) => boolean;
  canAccessTenant: (tenantId: string) => boolean;
  
  // 租户管理操作
  initializeTenant: (tenantId: string) => Promise<void>;
  clearTenantData: () => void;
}

export const useTenantStore = create<TenantState>()(
  persist(
    (set, get) => ({
      // 初始状态
      currentTenant: null,
      accessibleTenants: [],
      currentUser: null,
      token: null,
      isLoading: false,

      // 设置当前租户
      setCurrentTenant: (tenant: Tenant) => {
        set((state) => ({ ...state, currentTenant: tenant }));
        // 触发租户切换事件
        window.dispatchEvent(new CustomEvent('tenantChanged', { 
          detail: { tenant } 
        }));
      },

      // 设置可访问的租户列表
      setAccessibleTenants: (tenants: Tenant[]) => {
        set((state) => ({ ...state, accessibleTenants: tenants }));
      },

      // 设置当前用户
      setCurrentUser: (user: TenantUser) => {
        set({ currentUser: user });
      },

      // 设置token
      setToken: (token: string) => {
        set({ token });
        localStorage.setItem('token', token);
      },

      // 租户登录
      tenantLogin: async (loginData: TenantLoginRequest) => {
        set((state) => ({ ...state, isLoading: true }));
        
        try {
          const response = await authApi.tenantLogin(loginData);
          
          // 设置认证信息
          set({
            token: response.accessToken,
            currentUser: {
              id: response.user.id,
              tenantId: loginData.tenantCode,
              username: response.user.username,
              email: response.user.email,
              realName: response.user.realName || response.user.username,
              roles: response.user.roles?.map(role => typeof role === 'string' ? role : role.id) || [],
              teamIds: [],
              isSuperAdmin: false,
              status: response.user.status === 1 ? 'active' : response.user.status === 0 ? 'inactive' : 'locked',
              createTime: response.user.createTime || new Date().toISOString(),
              updateTime: response.user.updateTime || new Date().toISOString(),
            },
            isLoading: false,
          });
          
          // 存储到本地存储
          localStorage.setItem('token', response.accessToken);
          localStorage.setItem('tenant', JSON.stringify({ id: loginData.tenantCode, name: loginData.tenantCode }));
          
          message.success('租户登录成功！');
          
        } catch (error) {
          set((state) => ({ ...state, isLoading: false }));
          console.error('租户登录失败:', error);
          message.error('租户登录失败，请检查租户代码、用户名和密码');
          throw error;
        }
      },

      // 登出
      logout: () => {
        // 清除状态
        set((state) => ({
          ...state,
          token: null,
          currentUser: null,
          currentTenant: null,
          accessibleTenants: [],
          isLoading: false,
        }));
        
        // 清除本地存储
        localStorage.removeItem('token');
        localStorage.removeItem('currentTenant');
        localStorage.removeItem('currentUser');
        
        // 跳转到登录页
        window.location.href = '/login';
      },

      // 切换租户
      switchTenant: async (tenantId: string) => {
        const { accessibleTenants } = get();
        const targetTenant = accessibleTenants.find(t => t.id === tenantId);
        
        if (!targetTenant) {
          throw new Error('无法访问指定租户');
        }

        set((state) => ({ ...state, isLoading: true }));
        
        try {
          // 1. 设置当前租户
          set((state) => ({ ...state, currentTenant: targetTenant }));
          
          // 2. 重新加载用户权限（在新租户上下文中）
          await get().initializeTenant(tenantId);
          
          // 3. 清除旧的缓存数据
          // 这里可以清除其他相关的缓存，如菜单、权限等
          
        } catch (error) {
          console.error('切换租户失败:', error);
          throw error;
        } finally {
          set((state) => ({ ...state, isLoading: false }));
        }
      },

      // 刷新租户列表
      refreshTenants: async () => {
        set((state) => ({ ...state, isLoading: true }));
        
        try {
          // 这里调用API获取最新的租户列表
          // const tenants = await tenantApi.getAccessibleTenants();
          // set((state) => ({ ...state, accessibleTenants: tenants }));
          
          // 模拟API调用
          await new Promise(resolve => setTimeout(resolve, 1000));
          console.log('刷新租户列表完成');
          
        } catch (error) {
          console.error('刷新租户列表失败:', error);
          throw error;
        } finally {
          set((state) => ({ ...state, isLoading: false }));
        }
      },

      // 检查权限
      hasPermission: (permission: string, resourceContext?: any) => {
        const { currentUser, currentTenant } = get();
        
        if (!currentUser || !currentTenant) {
          return false;
        }

        // 超级管理员拥有所有权限
        if (currentUser.isSuperAdmin) {
          return true;
        }

        // 这里应该调用更复杂的权限验证逻辑
        // 包括 scope 和 condition 的检查
        return currentUser.roles.some(role => {
          // 简化的权限检查逻辑
          // 实际应该查询角色的具体权限并进行条件评估
          return role.includes(permission.split(':')[0]);
        });
      },

      // 检查角色
      hasRole: (role: string) => {
        const { currentUser } = get();
        return currentUser?.roles?.includes(role) || false;
      },

      // 检查是否可以访问指定租户
      canAccessTenant: (tenantId: string) => {
        const { currentUser, accessibleTenants } = get();
        
        if (!currentUser) {
          return false;
        }

        // 超级管理员可以访问所有租户
        if (currentUser.isSuperAdmin) {
          return true;
        }

        // 检查租户是否在可访问列表中
        return accessibleTenants.some(tenant => tenant.id === tenantId);
      },

      // 初始化租户数据
      initializeTenant: async (tenantId: string) => {
        try {
          // 1. 加载租户信息
          // const tenant = await tenantApi.getTenant(tenantId);
          
          // 2. 加载用户在该租户下的权限
          // const userPermissions = await tenantApi.getUserPermissions(tenantId);
          
          // 3. 更新状态
          // set({ currentTenant: tenant, currentUser: userPermissions });
          
          // 模拟API调用
          console.log('初始化租户数据:', tenantId);
          
        } catch (error) {
          console.error('初始化租户失败:', error);
          throw error;
        }
      },

      // 清除租户数据
      clearTenantData: () => {
        set((state) => ({
          ...state,
          currentTenant: null,
          accessibleTenants: [],
          currentUser: null,
          isLoading: false,
        }));
      },
    }),
    {
      name: 'tenant-storage',
      partialize: (state) => ({
        currentTenant: state.currentTenant,
        accessibleTenants: state.accessibleTenants,
        currentUser: state.currentUser,
        token: state.token,
      }),
    }
  )
);

// 租户权限Hook
export const useTenantPermissions = () => {
  const { 
    currentTenant, 
    currentUser, 
    hasPermission, 
    hasRole,
    canAccessTenant 
  } = useTenantStore();

  return {
    currentTenant,
    currentUser,
    hasPermission,
    hasRole,
    canAccessTenant,
    isInTenant: (tenantId: string) => currentTenant?.id === tenantId,
    isSuperAdmin: currentUser?.isSuperAdmin || false,
  };
};

// 租户上下文Hook
export const useTenantContext = () => {
  const {
    currentTenant,
    accessibleTenants,
    isLoading,
    switchTenant,
    refreshTenants,
    setCurrentTenant,
    setAccessibleTenants,
  } = useTenantStore();

  return {
    currentTenant,
    accessibleTenants,
    isLoading,
    switchTenant,
    refreshTenants,
    setCurrentTenant,
    setAccessibleTenants,
    hasMultipleTenants: accessibleTenants.length > 1,
  };
};